<template>
	<div class="payment">
		<div class="address">
			<x-input title="收货人" v-mtfocus v-model="name" text-align='right' placeholder="请填写收货人姓名"></x-input>
			<x-input title="手机号码" v-mtfocus v-model="phone" text-align='right' placeholder="请填写收货人手机号码"></x-input>
			<x-address title="地址" @on-shadow-change="onShadowChange" v-model="provinces" :list="ChinaAddressV4Data" placeholder="请选择"></x-address>
			<x-input class="border-none" v-mtfocus title="详细地址" v-model="address" text-align='right' placeholder="请输入街道，门牌等详细地址信息"></x-input>
		</div>
		<div class="goods">
			<div class="img">
				<img :src="goods.img">
			</div>
			<div class="title">
				<p class="tip">{{goods.title}}</p>
				<p class="price">¥{{goods.price}}</p>
			</div>
			<div class="num">x{{num}}</div>
		</div>
		<div class="goods-all" @click="show = !show">
			<span class="all-title">代金券</span>
			<span class="all-price"><span>已减 <em>{{coupons_price}}元</em></span> <em v-if="coupons">{{coupons.length}}</em> <em v-else>0 </em>张可用 <img src="@/assets/querengdingdan1.png"></span>
		</div>
		<div class="goods-all border-none">
			<span class="all-title">商品合计</span>
			<span class="all-price">￥{{num * goods.price}}</span>
		</div>
		<div class="btn">
			<span class="btn-price" v-if="">应付： ￥{{num * goods.price - coupons_price}}</span>
			<span class="btn-wx" @click="buy_goods"><!-- router({path: 'paysuccess'}) -->
				<img src="@/assets/kechenxiangqing5.png">
  			微信支付
			</span>
		</div>

    <div class="payment-transfer" v-transfer-dom>
      <popup v-model="show">
      	<div class="daijinquan">
      		<span class="cancer">取消</span>
      		<p>代金券</p>
      		<span class="confirm" @click="show = !show">确认</span>
      	</div>      	
				<div class="coupon-blocks" >
          <div v-if="coupons && coupons.length > 0">
  					<div class="coupon-block" v-for="(item, index) in coupons" :key="index" v-if="coupons && coupons.length > 0">
  						<span class="price">￥<em>{{item.money}}</em></span>
  						<div class="con">
  							<p class="con-price">￥{{item.title}}</p>
  							<p class="time">有效期至{{item.end_time | formatDate}}</p>
  						</div>
  						<span class="img" @click="mycouponsFn(index)" v-if="!item.img_block"><img src="@/assets/coupon-none.png"></span>
  						<span class="img" @click="mycouponsFn(index)" v-else><img src="@/assets/coupon-block.png"></span>
  					</div>
          </div>
          <div class="coupon-none" v-else>
            即刻参与活动赢取代金券前往 <span @click="router({path: 'activityCenter'})">活动中心 ></span>
          </div>      
				</div>  
      </popup>
    </div>
	</div>
</template>

<script>
import { XInput, XAddress, ChinaAddressV4Data, TransferDom, Popup, AlertModule  } from 'vux'
import { buy_good, mycoupons, get_goods_detail, baseUrl } from '@/api/api'
import { formatDate } from '@/util/date.js'
import { wexinPay } from '@/config/wxpay.js'
export default {
	filters:{
    formatDate(time){
      let date = new Date(time*1000);
      return formatDate(date,'yyyy.MM.dd');
      //此处formatDate是一个函数，将其封装在common/js/date.js里面，便于全局使用
    }
	},
  directives: {
    TransferDom,
    'mtfocus' (el, binding, vnode) {
      let mtinput = el.querySelector('input')
      mtinput.onfocus = function () {
				let btn = document.querySelector('.btn')
      	btn.className = "btn position_focus"
      }
      mtinput.onblur = function () {
				let btn = document.querySelector('.btn')
      	btn.className = "btn"
      }
    }
  },
  components: {
  	XInput,
  	XAddress,
  	ChinaAddressV4Data,
  	Popup
  },
  data () {
    return {
    	name: '',
    	phone: '',
    	address: '',
    	provinces: [],
    	ChinaAddressV4Data: ChinaAddressV4Data,
    	show: false,
    	coupons: [], //优惠券
    	coupons_price: '0', //优惠价格
      num: 0, //数量
      goods: {}
    }
  },
  created () {
  	this.num = this.$route.query.num
  	this.goods_id = this.$route.query.goods_id
  	this.mycouponsFn()
    this.get_goods_details()
  },
  methods: {    
    router (path) {
      this.$router.push(path)
    },
    // 地址id转文字
  	onShadowChange (ids, names) {
  		this.province = ''
  		for(var i = 0; i < names.length; i++){
  			this.province += names[i] + ' '
  		}
  	},
    // 获取代金券
    mycouponsFn (_index) {
    	mycoupons().then((res) => {
    		this.coupons = res.data.info
    		if(_index+1) {
    			// 选择优惠券
		    	for(var i in this.coupons){
		    		this.coupons[i].img_block = false
		    	}
    			this.coupons[_index].img_block = true
    			this.coupons_price = this.coupons[_index].money
    			this.coupons_id = this.coupons[_index].id
    		}
    	}).catch((err) => {
    		console.log(err)
    	})
    },
    // 下单
    buy_goods () {
      if(!sessionStorage.phone){
        this.$router.push({path: './bindPhone'})
        return
      }
    	if(this.provinces.length<1){
    		this.province = ''
    	}    	
      this.agent = (sessionStorage.pid) ? sessionStorage.pid : 0
    	var jsonData = {
    		goods: this.goods_id,
    		coupons: this.coupons_id,
    		num: this.num,
    		mobile: this.phone,
    		area: this.province.substring(0,this.province.length-1),
    		address: this.address,
    		consignee: this.name,
    		agent: this.agent
    	}
    	buy_good(jsonData).then((res) => {
        var order = res.data.info.order
        var data = res.data.info
    		if(res.data.status == 1){
          wexinPay(data, (res) => {
            AlertModule.show({
              title: '温馨提示',
              content: '购买成功',
              onHide: () => {
                this.$router.push({
                  path: 'paysuccess',
                  query: {
                    orderId: order
                  }
                })
              }
            })
          }, (err) => {
          })
    		}else{
    			AlertModule.show({
						title: '温馨提示',
						content: res.data.info
					})
    		}
    	}).catch((err) => {
    		console.log(err)
    	})
    },    
    get_goods_details () {
      get_goods_detail(this.goods_id).then((res) => {
        this.goods = res.data.info
      }).catch((err) => {
        console.log(err)
      })
    }
  }
}
</script>
<style lang="stylus">
.payment
  background-color #f2f2f2
  min-width 100vw
  min-height 100vh
  .address
    margin-bottom 1rem
    background-color #fff
    .weui-cell
      padding 0
      span
        font-size 1.5rem
        color #666
      .vux-cell-placeholder
        color #ccc
    .border-none
      border none !important
    .vux-x-input,.vux-cell-box
      padding 0
      line-height 5rem
      height 5rem
      overflow hidden
      margin 0 1.5rem
      border-bottom 1px solid #e5e5e5
      box-sizing border-box
      &::before
        display none
      label
        font-size 1.5rem
        color #666
      input
        font-size 1.5rem
        color #666
        line-height 3rem
        height 3rem
        margin-top 1rem    
        &::-webkit-input-placeholder
          color #ccc
  .goods
    display flex
    background-color #fff
    margin-bottom 1rem
    padding 2rem 1.5rem
    .img
      width 10rem
      height 7.5rem
      margin-right 1.4rem
    .title
      position relative
      max-width 17.5rem
      min-width 17.5rem
      .tip
        font-size 1.5rem
        color #333
        font-weight 500
      .price
        color #FF659B
        font-size 1.3rem
        line-height 1.6rem
        position absolute
        bottom 0px
    .num
      flex 1
      text-align right
      line-height 2.1rem
      font-size 1.5rem
      font-weight 500
  .goods-all
    background-color #fff
    line-height 5rem
    height 5rem
    display flex
    font-size 1.5rem
    padding 0 1.5rem
    border-bottom 1px solid #e5e5e5
    .all-title
      flex 1
      text-align left
      color #666
    .all-price
      flex 1
      text-align right
      color #333
      font-weight 500
      em
        color #FF659B
      img
        display inline-block
        height 1.3rem
        width auto
        vertical-align middle
        position relative
        top -.1rem
  .border-none
    border none
  .btn
    height 5rem
    line-height 5rem
    position absolute
    bottom 0
    width 100%
    display flex
    left 0
    .btn-price
      width 64%
      background-color #FF659B
      color #fff
      font-size 1.6rem
      line-height 5rem
      padding-left 1.5rem
      box-sizing border-box
      text-align left
    .btn-wx
      width 36%
      background-color #9F7FFF
      color #fff
      text-align center
      font-size 1.5rem
      img
        height 2rem
        width auto
        display inline-block
        vertical-align middle
        position relative
        top -.2rem
  .position_focus.btn
    position absolute
    margin-top 2rem
    bottom auto
</style>